const prizeTool = {};
const RuleService = require('../../service/prize/RuleService');
const RecordService = require('../../service/prize/RecordService');
const EventService = require('../../service/prize/EventService');
const CountService = require('../../service/prize/CountService');
const resUtil = require("../../module/util/resUtil");
const logger = require('log4js').getLogger("sys");
const request = require('request');
const xml2json = require('basic-xml2json');
var iconv = require("iconv-lite");


prizeTool.getPrizeResult = function (n, ruleList,user) {
    return new Promise((res,rej)=>{
        console.log('come in Promise........');
        console.log('rulelist is......');
        console.log(ruleList);
        let random = (Math.random() * n);
        console.log(random+'random');
        let min = 0, max;
        for (let i = 0; i < ruleList.length; i++) {
            max = min + (ruleList[i].chance - 0);
            if (random >= min && random <= max) {
                // if (ruleList[i].prizeType === 'prize' && ruleList[i].remainCount === 0) {
                if ( ruleList[i].remainCount === 0) {
                    console.log('step1');
                    res({result:false})
                } else {
                    console.log('step2');
                    if(ruleList[i].prizeNumber==0||!ruleList[i].prizeNumber){
                        console.log('step2.1');
                        console.log(ruleList[i]);
                        console.log('come in Promise1........');
                        res({result:ruleList[i]});
                    }else{
                        console.log('step2.2');
                        RecordService.find(user,{customer:user,prize:ruleList[i]._id}).then(records=>{
                            if(records.length<ruleList[i].prizeNumber){
                                console.log('come in Promise2.......x`.');
                                console.log(ruleList[i]);
                                res({result:ruleList[i]})
                            }else{
                                console.log('step2.3');
                                res({result:false});
                            }
                        })
                    }
                }
            } else {
                min += (ruleList[i].chance - 0);
                if(i == ruleList.length-1){
                    res({result:false});
                }
            }
        }
    })
    // return false;
};
prizeTool.saveRecord = function (cus, prizeRule,oa,expireTime,needPoint,gameType) {
    return new Promise((resolve, reject) => {
        console.log(cus);
        let data = {};
        let result = {
            customer: cus.openid,
            vipName: cus.vipName,
            eventId: prizeRule.eventId||prizeRule._id,
            officialAccount:oa,
            expireTime:expireTime,
            cardCode:cus.cardCode,
            mobile:cus.mobile,
            gameType:gameType
        };
        if(prizeRule.rule){
            result.prize=prizeRule._id
        }
        let eventRecordSave = function () {
            RecordService.save({}, result).then(() => {
                resolve(result);
            }, (err) => {
                reject(err);
            });
        };
        let updateCount = (prizeRule)=>{
            return new Promise((resolve,reject)=>{
                if(prizeRule.remainCount){
                    RuleService.updateById({}, prizeRule._id, {remainCount: `${prizeRule.remainCount-1}`}).then(ruleResult => {
                        resolve(ruleResult)
                    },err=>{reject(err)})
                }else{
                    resolve();
                }
            })
        }
        if (prizeRule.prizeType === 'prize') {
            result.info = prizeRule.priceName;
            updateCount(prizeRule).then(data=>{
                eventRecordSave();
            },err=>{
                res.send(resUtil.error({}));
            })

        } else {
            if(prizeRule.prizeType === 'point'){
                updateCount(prizeRule).then(data=>{
                    request({
                        method: 'get',
                        uri: `${global.config.pos.endpoint}/cardPointLottery?cardCode=${cus.cardCode}&point=${prizeRule.point}&operType=2`,
                        json: true
                    }, function (e, response, data) {
                        if(!data){
                            res.send(resUtil.error({}));
                            return;
                        }
                        let jsonStr = xml2json.parse(data);
                        let json = JSON.parse(jsonStr.root.content);
                        logger.info(json.ResultValue[0].errMsg);
                        console.log(json.ResultValue[0].errMsg+'调用erp积分返回');
                        if(json.ResultCode==='0'){
                            result.point = prizeRule.point;
                            result.awardFlag = 1;
                            result.curUserPoint =  json.ResultValue[0].errMsg.currPoint;
                            eventRecordSave();
                        }else{
                            reject({err:json.ResultValue[0].errMsg})
                        }
                    });
                },err=>{

                })
            }else if(prizeRule.prizeType === 'coupon'){
                updateCount(prizeRule).then(data=>{
                    let url=global.config.pos.endpoint+'/buildGiftCodeNew?cardCode='+cus.cardCode+'&giftTypeCode='+prizeRule.giftCode;
                    let rawStr = iconv.encode(url, 'utf-8').toString('binary');
                    request({
                        method: 'get',
                        uri: rawStr,
                        json: true,
                    }, function (e, response, data) {
                        if(!data){
                            res.send(resUtil.error({}));
                            return;
                        }
                        console.log(rawStr);
                        let jsonStr = xml2json.parse(data);
                        let json = JSON.parse(jsonStr.root.content);
                        logger.info(json.ResultValue[0].errMsg.giftCode);
                        result.giftCode = json.ResultValue[0].errMsg.giftCode;
                        result.awardFlag = 1;
                        if(json.ResultCode==='0'){
                            eventRecordSave();
                        }else{
                            reject(json.ResultValue[0].errMsg)
                        }
                    });
                })

            }
            else{
                result.awardFlag = 3;
                eventRecordSave();
            }
        }
    });
};

module.exports = prizeTool;